<template>
  <div id="index" ref="appRef">
    <div class="bg">
      <dv-loading v-if="loading">Loading...</dv-loading>
      <div v-else class="host-body">
        <div class="d-flex jc-center">
          <dv-decoration-10 class="dv-dec-10" />
          <div class="d-flex jc-center">
            <dv-decoration-8 class="dv-dec-8" :color="decorationColors" />
            <div class="title">
              <span class="title-text">浦江病区概览</span>
              <dv-decoration-6
                class="dv-dec-6"
                :reverse="true"
                :color="['#50e3c2', '#67a1e5']"
              />
            </div>
            <dv-decoration-8
              class="dv-dec-8"
              :reverse="true"
              :color="decorationColors"
            />
          </div>
          <dv-decoration-10 class="dv-dec-10-s" />
        </div>

        <!-- 第二行 -->
        <div class="d-flex jc-between px-2">
          <div class="d-flex aside-width">
            <div class="react-left ml-4 react-l-s">
              <span class="react-before"></span>
              <span class="text" @click="goToHomePage">返回首页</span>
              <span class="text" @click="goToFenYangWardPage">汾阳</span>
            </div>
            <div class="react-left ml-3" style="width: 260px">
              <span class="text">{{ subtitle[1] }}</span>
            </div>
          </div>
          <div class="d-flex aside-width">
            <div
              class="react-right mr-3"
              style="background-color: #0f1325; width: 250px"
            >
              <span class="text fw-b">{{ subtitle[2] }}</span>
            </div>
            <div class="react-right mr-4 react-l-s">
              <span class="react-after"></span>
              <span class="text">
                {{ timeInfo.dateYear }} {{ timeInfo.dateWeek }}
                {{ timeInfo.dateDay }}
              </span>
            </div>
          </div>
        </div>
        <div class="body-box scrollable-content">
        <div class="body-box">
          <div class="WardBox">
            <!-- 只渲染有数据的科室 -->
            <WardView
              v-for="(dept, index) in departments"
              :key="index"
              :title="dept.deptName"
              :statistics="getDeptStatistics(dept.deptName)"
            />
            
          </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
  
<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onUnmounted } from "vue";
import { formatTime } from "@/utils/index";
import { WEEK } from "@/constant/index";
import useDraw from "@/utils/useDraw";
import { title, subtitle, moduleInfo } from "@/constant/index";
import WardView from "./WardView.vue";
import axios from "axios";

export default defineComponent({
  components: {
    WardView,
  },
  setup() {
    // 定义接口数据类型
    interface StatisticsItem {
      id: any;
      iiiDataType: string;
      number: string;
      lastWeekNum: string;
      deptName: string;
    }
    interface Department {
      deptName: string;
    }

    interface ApiResponse {
      fullStatistics: StatisticsItem[];
      departmentsOnly: Department[];
    }

    // 存储接口数据
    const departments = ref<Department[]>([]);
    const fullStatistics = ref<StatisticsItem[]>([]);

    // 颜色配置
    const decorationColors = ["#568aea", "#000000"];
    // 加载状态
    const loading = ref<boolean>(true);
    // 时间信息
    const timeInfo = reactive({
      setInterval: 0,
      dateDay: "",
      dateYear: "",
      dateWeek: "",
    });
    // 适配处理
    const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw();

    onMounted(async () => {
      try {
        // 调用接口获取数据
        const response = await axios.get<ApiResponse>(
          window.globalConfig.baseApi +"/api/Nurse/GetStatisticsDataJsonByDeptGL?dbKey=dbPJ"
        );
        const data = response.data;

        // 验证并处理接口返回数据
        if (Array.isArray(data.departmentsOnly)) {
          departments.value = data.departmentsOnly;
        }
        if (Array.isArray(data.fullStatistics)) {
          fullStatistics.value = data.fullStatistics;
        }

        console.log("接口返回科室列表:", departments.value);
        console.log("接口返回统计数据:", fullStatistics.value);

      } catch (error) {
        console.error("接口请求失败:", error);
        // 错误状态下显示默认科室（可选）
        departments.value = [{ deptName: "默认科室" }];
      } finally {
        cancelLoading();
        handleTime();
        windowDraw();
        calcRate();
      }
    });

    // 根据科室名称筛选并格式化统计数据
    const getDeptStatistics = (deptName: string) => {
      if (!deptName || !fullStatistics.value.length) return [];
      
      return fullStatistics.value
        .filter(item => 
          item?.deptName === deptName && 
          typeof item.iiiDataType === 'string' && 
          item.number !== undefined
        )
        .map(item => ({
          name: item.iiiDataType.trim(), // 去除空格
          value: Number(item.number) || 0 // 确保数值有效
        }));
    };

    onUnmounted(() => {
      unWindowDraw();
      clearInterval(timeInfo.setInterval);
    });

    // 取消加载状态
    const cancelLoading = () => {
      setTimeout(() => {
        loading.value = false;
      }, 500);
    };

    // 处理时间更新
    const handleTime = () => {
      timeInfo.setInterval = window.setInterval(() => {
        const date = new Date();
        timeInfo.dateDay = formatTime(date, "HH: mm: ss");
        timeInfo.dateYear = formatTime(date, "yyyy-MM-dd");
        timeInfo.dateWeek = WEEK[date.getDay()] || "";
      }, 1000);
    };

    return {
      loading,
      timeInfo,
      appRef,
      title,
      subtitle,
      moduleInfo,
      departments,
      getDeptStatistics,
      decorationColors
    };
  },
  methods: {
    goToHomePage() {
      this.$router.push({ name: "Index" });
    },
    goToFenYangWardPage() {
      this.$router.push({ name: "FenYangWard" });
    },
  },
});
</script>
  
<style lang="scss" scoped>
@import "../inpatientsDetailsCSS/FenYangWard.scss";

.scrollable-content {
    // 设置最大高度，超出部分可滚动
    max-height: 90%; // 根据实际页面布局调整
    overflow-y: auto;
  overflow-x: hidden; // 禁止横向滚动
    // 美化滚动条
    scrollbar-width: thin;
    scrollbar-color: #568aea #0f1325;
  }

  // WebKit 浏览器滚动条样式
  .scrollable-content::-webkit-scrollbar {
    width: 6px;
  }

  .scrollable-content::-webkit-scrollbar-track {
    background: #0f1325;
    border-radius: 3px;
  }

  .scrollable-content::-webkit-scrollbar-thumb {
    background-color: #568aea;
    border-radius: 3px;
  }

  // 确保内容区域有足够的内边距，避免内容紧贴边缘
  .body-box {
    padding-bottom: 20px;
  }

// 科室容器布局
.WardBox {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); // 自适应列数
  gap: 15px; // 网格间距
  padding: 10px;
}

// 无数据提示样式
.empty提示 {
  height: 350px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #eaedf3;
  background: rgba(15, 19, 37, 0.3);
  border-radius: 4px;
}
</style>